import React from 'react'
import {ActivityIndicator,Icon,Tools,Modal} from 'weaver-mobile'
import DocConstant from "../util";
import * as API from '../api/doc'
const getLabel = Tools.getLabel;

//获取wps签名
export const getWpsSign = (ifrId) => {
	if(!ifrId){
		return;
	}
	var ifrmDom = document.getElementById(ifrId); 
	if(!ifrmDom || ifrmDom.length == 0){
		return;
	}
	
	var _src = ifrmDom.src;
	if(!_src || _src.indexOf("&appid=") == -1){
		return;
	}
	
	var _expIndex = _src.indexOf("?");
	var _expires = _src.substring(_expIndex+1);
	_expires = decodeURIComponent(_expires).replace(/&/g,"^_^");
	API.getWpsSign({sign:_expires}).then(data=>{
		if(data && data.status == 1){
			var pdata = {};
			for(var k in data.params){
				pdata[k] = data.params[k];
			}
			var sendData = JSON.stringify({"action":"logic.setToken", data:pdata});
			ifrmDom.contentWindow.postMessage(sendData, '*');
			setTimeout(()=>{
	      		getWpsSign(ifrId);
	       	},data.timeout);
		}else{
			//getWpsSign(ifrId);
		}
	})
	
}

//ListView的上拉加载新数据loading效果方法
export const ListViewLoading = (loading,Datasource) => (
    loading 
    ? Datasource.getRowCount() === 0 
        ? <div className="wea-doc-error"><ActivityIndicator /></div> 
        :<div className="wea-doc-error-line"><ActivityIndicator /></div>
    : Datasource.getRowCount() === 0 
        ? <div className="wea-doc-error">
          <Icon type="no-data" size="lg"/>
          <div>{getLabel(83553, '暂无数据')}</div>
        </div> 
        : null
)
//获取url中指定的参数
export const GetUrlParam = (url,paraName) => {
    let arrObj = url.split("?");
    if (arrObj.length > 1) {
        let arrPara = arrObj[1].split("&");
        let arr;
        for (let i = 0; i < arrPara.length; i++) {
            arr = arrPara[i].split("=");
            if (arr !== null && arr[0] === paraName) {
                return arr[1];
            }
        }
        return "";
    }else {
        return "";
    }
}
//em7设置title
export const SetTitle = (title,prevTitle,that) => {
    prevTitle = prevTitle || '';
    if (title) {
        if (DocConstant.isApp()) {
          new Promise((resolve, reject) => {
            window.em.getTitle({'success':function (argument) {
              resolve(argument);
            },'fail':function (argument) {
              reject(argument);
            }});
          }).then((res) => {
            that.prevTitle = res && res.result;
          }).catch(() => {
            that.prevTitle = prevTitle;
          });
          window.em.changeTitle({
            title: title
          });
        } else {
            that.prevTitle = window.document.title;
          window.document.title = title;
        }
      }
}
//判断附加是否可以下载的提示
export const attachAlert = (attach,docInfo,fileurl) => {
    docInfo.candownload
    ? (docInfo.doc_acc_isdownload || '1') === '0'
      ? Modal.alert(getLabel(24960,'提示信息'), getLabel(391349, "您查看的文件已被配置不可预览时不能下载，请联系管理员了解详情"), [
        { text: getLabel(826, '确定'), onPress: () => {}}
      ])
      : docInfo.doc_acc_download_noalert === '1'
        ?attach.tooLarge === '0'
          ? Modal.alert(getLabel(24960,'提示信息'), getLabel(391350, "您查看的文档不能直接打开,是否下载查看?"), [
            { text: getLabel(31129, '取消')},
            { text: getLabel(826, '确定'), onPress: () => {
              downloadFile(fileurl,attach.imagefileid);
              }
            },
          ])
          : Modal.alert(getLabel(24960,'提示信息'), getLabel(516297, "您查看的文档过大，暂不能直接打开,是否下载查看?"), [
            { text: getLabel(31129, '取消')},
            { text: getLabel(826, '确定'), onPress: () => {
              downloadFile(fileurl,attach.imagefileid);
              }
            },
          ])
        :downloadFile(fileurl,attach.imagefileid)
    : Modal.alert(getLabel(24960,'提示信息'), getLabel(509650, "您查看的文件不能直接打开，请联系创建人获取下载权限后查看"), [
      { text: getLabel(826, '确定'), onPress: () => {}}
    ])
}
export const delUrlParams = (url,paramsname) =>{
  if (url.indexOf(paramsname)>-1) {
      let obj = {}
      let arr = url.split("&");
      for (let i = 0; i < arr.length; i++) {
          arr[i] = arr[i].split("=");
          arr[i][2] ? obj[arr[i][0]] = arr[i][1] + "=" + arr[i][2] : obj[arr[i][0]] = arr[i][1];
      };
      delete obj[paramsname];
      let result =  JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
      return result
  };
}
export const downloadFile = (url,imagefileid) => {
  const isiPhone = Tools.mobileDetect().is('iPhone');
  let em_auth_code = GetUrlParam(url,"em_auth_code");
  if(em_auth_code!==""){
    url = delUrlParams(url,"em_auth_code");
  }
  Tools.getWeaverFile(url);
  // if(isiPhone){
  //   API.getDownloadParams({fileid:imagefileid}).then(result=>{
  //     if(result && result.params){
  //       url = url + result.params;
  //     }
  //     if(window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')){
  //       window.em.openLink({
  //         url:url,
  //         openType:1
  //       });
  //     }else{
  //       var _win = window;
  //       _win.location = url;
  //     }
  //   });
  // }else{
  //   Tools.getWeaverFile(url,'iframe');
  // }
}
export const openHrmCard = (id) => {
  if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
    window.em.openLink({
      url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
      openType: 2,
      sysId: window.localStorage.emobile_ec_id,
    });
  }else{
    window.open( `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`);
  }
  //window.openLink(`/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`);
}

export const openAttachPage = (fileid,params) => {
  if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
    window.em.openLink({
      url: `/spa/document/static4mobile/index.html#/attach/${fileid}`+(params?params:""),
      openType: 2,
      sysId: window.localStorage.emobile_ec_id,
    });
  }else{
    let url = `/spa/document/static4mobile/index.html#/attach/${fileid}`+(params?params:"")
    window.open(url);
  }
  //window.openLink(`/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`);
}